<template>
  <div class="acupoint-list-container">
    <Table
      v-loading="loading"
      :columns="columns"
      :data-source="dataSource"
      :count="0"
      :page-no.sync="query.pageNo"
      :page-size.sync="query.pageSize"
      :request="request"
      :list="list"
      :form-data.sync="formData"
      :button-group="buttonGroup"
      :table-props="tableProps"
    />

    <el-dialog :visible.sync="dialogVisible" title="添加穴位" width="800px">
      <PageForm
        ref="dialogForm"
        :form-data.sync="ruleForm"
        :list="pageList"
        :rules="dialogRules"
        label-position="top"
      />
    </el-dialog>

    <el-dialog :visible.sync="dialogEditVisible" title="编辑穴位" width="800px">
      <PageForm
        ref="dialogEditForm"
        :form-data.sync="ruleForm"
        :list="pageEditList"
        :rules="dialogRules"
        label-position="top"
      />
    </el-dialog>
  </div>
</template>

<script>
import Table from "@/components/Table";
import PageForm from "@/components/PageForm";
import {
  getAcupointTreeListApi,
  addAcupointApi,
  updateAcupointApi,
  deleteAcupointApi,
} from "../../../api/config/acupoint";
import { treeToArrayOptimized } from "@/utils/treeToArray";

export default {
  name: "AcupointList",
  components: {
    Table,
    PageForm,
  },
  data() {
    return {
      dialogVisible: false,
      dialogEditVisible: false,
      query: {
        pageNo: 1,
        pageSize: 10,
      },
      loading: false,
      dataSource: [],
      count: 0,
      formData: {
        acupointText: "",
      },
      ruleForm: {
        acupointCode: "",
        acupointText: "",
        parentCode: "",
        acupointType: "",
        locationType: "",
        sideType: "",
        sortNum: "",
      },
    };
  },
  computed: {
    treeArray() {
      if (!this.dataSource || !Array.isArray(this.dataSource)) return [];

      return treeToArrayOptimized(this.dataSource);
    },
    // 表格属性配置，支持树形结构
    tableProps() {
      return {
        rowKey: "acupointCode",
        defaultExpandAll: true,
        treeProps: { children: "children", hasChildren: "hasChildren" },
      };
    },
    // 搜索表单配置
    list() {
      return [
        {
          list: [
            {
              span: 6,
              label:"穴位名称",
              prop: "acupointText",
              component: "input",
              componentProps: {
                placeholder: "请输入穴位名称",
              },
            },
          ],
        },
      ];
    },
    // 表格列配置
    columns() {
      return [
        {
          prop: "acupointCode",
          label: "穴位编码",
        },
        {
          prop: "acupointText",
          label: "穴位名称",
        },
        {
          prop: "acupointType",
          label: "穴位类型",
          type: "enum",
          enumName: "acupointTypeEnum",
        },
        {
          prop: "locationType",
          label: "位置类型",
          type: "enum",
          enumName: "acupointLocationTypeEnum",
        },
        {
          prop: "sideType",
          label: "穴位侧别",
          type: "enum",
          enumName: "acupointSideTypeEnum",
        },
        {
          prop: "sortNum",
          label: "排序",
        },
        {
          prop: "action",
          label: "操作",
          type: "action",
          width: 300,
          componentProps: {
            fixed: "right",
          },
          buttonGroup: [
            {
              label: "添加子项",
              type: "primary",
              size: "small",
              statusName: ["acupointType"],
              status: "meridian",
              click: (row) => {
                this.dialogVisible = true;
                this.resetForm();
                this.ruleForm.parentCode = row.acupointCode;
              },
            },
            {
              label: "编辑",
              type: "primary",
              size: "small",
              click: (row) => {
                this.dialogEditVisible = true;
                this.ruleForm = { ...row };
              },
            },
            {
              label: "删除",
              type: "danger",
              size: "small",
              click: (row) => {
                this.$confirm("此操作将删除此穴位, 是否继续?", "提示", {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "warning",
                }).then(async () => {
                  try {
                    await deleteAcupointApi({ acupointCode: row.acupointCode });
                    this.$message.success("删除成功");
                    this.request();
                  } catch (error) {
                    this.$message.error("删除失败");
                  }
                });
              },
            },
          ],
        },
      ];
    },
    // 按钮组配置
    buttonGroup() {
      return [
        {
          label: "添加",
          type: "primary",
          click: () => {
            this.resetForm();
            this.ruleForm.parentCode = "0";
            this.dialogVisible = true;
          },
        },
      ];
    },
    // 添加表单配置
    pageList() {
      return [
        {
          list: [
            {
              span: 24,
              prop: "parentCode",
              label: "父级穴位编码",
              component: "Treeselect",
              treeSelectList: [
                {
                  acupointCode: "0",
                  acupointText: "顶级穴位",
                  children: this.dataSource || [],
                },
              ],
              normalizer(node) {
                if (node.children && !node.children.length) {
                  delete node.children;
                }
                // 兼容不同的数据结构
                return {
                  id: node.acupointCode,
                  label: node.acupointText,
                  children: node.children,
                };
              },
              componentProps: {
                placeholder: "请选择父级穴位",
              },
            },
            {
              span: 24,
              prop: "acupointCode",
              label: "穴位编码",
              component: "input",
              componentProps: {
                placeholder: "请输入穴位编码",
              },
            },
          ],
        },
        {
          list: [
            {
              span: 24,
              prop: "acupointText",
              label: "穴位名称",
              component: "input",
              componentProps: {
                placeholder: "请输入穴位名称",
              },
            },
            {
              span: 24,
              prop: "acupointType",
              label: "穴位类型",
              component: "enum",
              enumName: "acupointTypeEnum",
            },
          ],
        },
        {
          list: [
            {
              span: 24,
              prop: "locationType",
              label: "位置类型",
              component: "enum",
              enumName: "acupointLocationTypeEnum",
            },
            {
              span: 24,
              prop: "sideType",
              label: "穴位侧别",
              component: "enum",
              enumName: "acupointSideTypeEnum",
            },
          ],
        },
        {
          list: [
            {
              span: 24,
              prop: "sortNum",
              label: "排序",
              component: "input",
              componentProps: {
                type: "number",
                placeholder: "请输入排序",
              },
            },
          ],
        },
        {
          list: [
            {
              span: 24,
              label: "",
              prop: "action",
              component: "action",
              componentProps: [
                {
                  label: "取消",
                  type: "default",
                  click: () => {
                    this.dialogVisible = false;
                    this.resetForm();
                  },
                },
                {
                  label: "确定",
                  type: "primary",
                  click: () => {
                    if (this.$refs.dialogForm) {
                      this.$refs.dialogForm.validate((valid) => {
                        if (valid) {
                          this.handleSave();
                        }
                      });
                    }
                  },
                },
              ],
            },
          ],
        },
      ];
    },
    // 编辑表单配置
    pageEditList() {
      return [
        {
          list: [
            {
              span: 24,
              prop: "parentCode",
              label: "父级穴位编码",
              component: "Treeselect",
              treeSelectList: [
                {
                  acupointCode: "0",
                  acupointText: "顶级穴位",
                  children: this.dataSource || [],
                },
              ],
              normalizer(node) {
                if (node.children && !node.children.length) {
                  delete node.children;
                }
                // 兼容不同的数据结构
                return {
                  id: node.acupointCode,
                  label: node.acupointText,
                  children: node.children,
                };
              },
              componentProps: {
                placeholder: "请选择父级穴位",
              },
            },
            {
              span: 24,
              prop: "acupointCode",
              label: "穴位编码",
              component: "input",
              componentProps: {
                placeholder: "请输入穴位编码",
              },
            },
          ],
        },
        {
          list: [
            {
              span: 24,
              prop: "acupointText",
              label: "穴位名称",
              component: "input",
              componentProps: {
                placeholder: "请输入穴位名称",
              },
            },
            {
              span: 24,
              prop: "acupointType",
              label: "穴位类型",
              component: "enum",
              enumName: "acupointTypeEnum",
            },
          ],
        },
        {
          list: [
            {
              span: 24,
              prop: "locationType",
              label: "位置类型",
              component: "enum",
              enumName: "acupointLocationTypeEnum",
            },
            {
              span: 24,
              prop: "sideType",
              label: "穴位侧别",
              component: "enum",
              enumName: "acupointSideTypeEnum",
            },
          ],
        },
        {
          list: [
            {
              span: 24,
              prop: "sortNum",
              label: "排序",
              component: "input",
              componentProps: {
                type: "number",
                placeholder: "请输入排序",
              },
            },
          ],
        },
        {
          list: [
            {
              span: 24,
              label: "",
              prop: "action",
              component: "action",
              componentProps: [
                {
                  label: "取消",
                  type: "default",
                  click: () => {
                    this.dialogEditVisible = false;
                    this.resetForm();
                  },
                },
                {
                  label: "确定",
                  type: "primary",
                  click: () => {
                    if (this.$refs.dialogEditForm) {
                      this.$refs.dialogEditForm.validate((valid) => {
                        if (valid) {
                          this.handleUpdate();
                        }
                      });
                    }
                  },
                },
              ],
            },
          ],
        },
      ];
    },
    // 表单验证规则
    dialogRules() {
      return {
        acupointCode: [
          { required: true, message: "请输入穴位编码", trigger: "blur" },
        ],
        acupointText: [
          { required: true, message: "请输入穴位名称", trigger: "blur" },
        ],
        acupointType: [
          { required: true, message: "请选择穴位类型", trigger: "change" },
        ],
        locationType: [
          { required: true, message: "请选择位置类型", trigger: "change" },
        ],
        parentCode: [
          { required: true, message: "请选择父级穴位编码", trigger: "change" },
        ],
        sideType: [
          { required: true, message: "请选择穴位侧别", trigger: "change" },
        ],
        sortNum: [{ required: true, message: "请输入排序", trigger: "blur" }],
      };
    },
  },
  methods: {
    // 请求数据
    async request() {
      try {
        if (this.loading) return;

        this.loading = true;

        const res = await getAcupointTreeListApi({
          acupointText: this.formData.acupointText,
        });

        if (res.code !== 200) {
          this.$message.error(res.msg);
          return;
        }

        this.dataSource = res.data || [];
        this.count = this.dataSource.length;
      } catch (error) {
        console.log(error);
        this.$message.error("获取穴位列表失败");
      } finally {
        this.loading = false;
      }
    },
    // 处理保存
    async handleSave() {
      try {
        if (this.loading) return;
        this.loading = true;

        const res = await addAcupointApi(this.ruleForm);

        this.loading = false;
        if (res.code === 200) {
          this.$message.success("添加成功");
          this.dialogVisible = false;
          this.resetForm();
          this.request();
        }
      } catch (error) {
        this.loading = false;
        console.error(error);
      }
    },
    // 处理更新
    async handleUpdate() {
      try {
        if (this.loading) return;
        this.loading = true;

        const res = await updateAcupointApi(this.ruleForm);

        this.loading = false;

        if (res.code === 200) {
          this.$message.success("更新成功");
          this.dialogEditVisible = false;
          this.resetForm();
          this.request();
        }
      } catch (error) {
        this.loading = false;
        console.error(error);
      }
    },
    // 重置表单
    resetForm() {
      this.ruleForm = {
        acupointCode: "",
        acupointText: "",
        parentCode: "",
        acupointType: "",
        locationType: "",
        sideType: "",
        sortNum: "",
      };
    },
  },
};
</script>

<style lang="scss" scoped>
.acupoint-list-container {
  padding: 20px;
}
</style>
